package com.apes.fn.server.productRequire;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.scm.masterdata.product.repository.ProductRepository;
import com.apestech.framework.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

@Service("requireLogisticsService")
public class RequireLogisticsService extends DomainService {

    @Autowired
    private RequireInfoConfigurRepository requireInfoConfigurRepository;
    @Autowired
    private ProductRepository productRepository;
    @Autowired
    private RequireLogisticsRepository requireLogisticsRepository;

    public void create(SimpleRequest request) {
        JSONArray getJA = request.getJA();
        List<RequireInfoConfigur> requireInfoConfigurs = requireInfoConfigurRepository.findAll(JpaDsl.toCriteriaByEq("valid", true));
        requireInfoConfigurs.forEach(singleRequireInfoCOnfigur -> {
            RequireInfoConfigur requireInfoConfigur = (RequireInfoConfigur) singleRequireInfoCOnfigur;
            String businessTypeId = requireInfoConfigur.getBusinessType().getId();
            String parameterStr = requireInfoConfigur.getParameter();
            String configurState = requireInfoConfigur.getBusinessAttributeValue().getCode();
            String upBusinessTypeId = requireInfoConfigur.getUpBusinessType() == null?"":requireInfoConfigur.getUpBusinessType().getId();

            AtomicReference newMessage = new AtomicReference();
            getJA.stream().anyMatch(singleItem -> {
                JSONObject item = (JSONObject) singleItem;
                String iUpBusinessTypeId = item.getString("upBusinessTypeId");
                if (!(item.getString("innerBusinessType").equals(businessTypeId) && item.getString("state").equals(configurState) &&
                        ((StringUtils.isEmpty(iUpBusinessTypeId) && StringUtils.isEmpty(upBusinessTypeId)) || (StringUtils.hasText(iUpBusinessTypeId) && upBusinessTypeId.equals(iUpBusinessTypeId))))) return true;
                newMessage.set(this.getMessage(item, parameterStr, requireInfoConfigur.getMessage()));
                if (businessTypeId.equals("Waybill") && requireInfoConfigur.isOneMark()) {
                    if (requireLogisticsRepository.distinctRequireLogistics(item.getString("id"), newMessage.get().toString()).size() > 0) return true;
                }

                RequireLogistics requireLogistics = this.appendRequireLogistics(item, requireInfoConfigur, String.valueOf(newMessage.get()));
                requireLogisticsRepository.saveAndFlush(requireLogistics);
                if (requireInfoConfigur.isOneMark() && StringUtils.isEmpty(item.getString("itemIsOneMark"))) return true;

                return false;
            });
        });
    }

    private String getMessage(JSONObject item, String parameterStr, String message) {
        if (message.indexOf("%s") == -1) return message;
        String[] parameters = parameterStr.split(";");
        if (parameters.length == 0) throw new RuntimeException("请在 要货物流参数配置 界面 配置 [参数]！");
        if (parameters.length != 0) return String.format(message, this.getMessageValue(parameters, item));
        return message;
    }

    private String[] getMessageValue(String[] parameters, JSONObject item) {
        String[] values = new String[parameters.length];
        for (int i = 0, iLen = parameters.length; i < iLen; i++) {
            values[i] = String.valueOf(item.get(parameters[i]));
        }
        return values;
    }

    public void oldCGDDSave(SimpleRequest request) {
        JSONObject getJO = request.getJO();
        JSONArray itemArray = getJO.getJSONArray("item");
        for (int i = 0, iLen = itemArray.size(); i < iLen; i++) {
            JSONObject item = itemArray.getJSONObject(i);
            RequireInfoConfigur requireInfoConfigur = new RequireInfoConfigur();
            requireInfoConfigur.setOneMark(item.getBooleanValue("oneMark"));
            requireLogisticsRepository.saveAndFlush(this.appendRequireLogistics(item, requireInfoConfigur, item.getString("message")));
        }
    }

    private RequireLogistics appendRequireLogistics(JSONObject getJO, RequireInfoConfigur requireInfoConfigur, String message) {
        RequireLogistics requireLogistics = new RequireLogistics();
        requireLogistics.setSource(getJO.getString("source"));
        requireLogistics.setSourceType(getJO.getString("sourceType"));
        requireLogistics.setOrigin(getJO.getString("origin"));
        requireLogistics.setOriginBusinessType(getJO.getString("originBusinessType"));
        requireLogistics.setMessage(message);
        if (requireInfoConfigur.isOneMark()) return requireLogistics;
        requireLogistics.setProduct(productRepository.findOne(getJO.getString("productId")));
        return requireLogistics;

    }

    public List<Map> findIdRequireLogistics(SimpleRequest request) {
        JSONObject getData = (JSONObject) request.getData();
        List<Map> resultData = requireLogisticsRepository.findOneRequireLogistics(getData.getString("ID"),
                getData.getString("PRODUCT_ID"));
        return resultData;

    }

    /**
     * 新增要货跟踪
     * @param request
     */
    public void save(SimpleRequest request){
        JSONObject jo = request.getJO();
        RequireLogistics requireLogistics = new RequireLogistics();
        requireLogistics.setSource(jo.getString("source"));
        requireLogistics.setOrigin(jo.getString("origin"));
        requireLogistics.setMessage(jo.getString("message"));
        if (StringUtil.isNotEmpty(jo.getString("productId"))) {
            requireLogistics.setProduct(productRepository.findOne(jo.getString("productId")));
        }
        requireLogisticsRepository.saveAndFlush(requireLogistics);
    }

}



















